#include <stdlib.h>
#include <stdio.h>
#include <math.h>

int main(int argc, char *argv[])
{
  int i, j, nbin=0, *na[8];
  int Lbox;
  double lmmin, lmmax, dlm, m, x[3], s, s2, *ma;
  char string[1000];
  FILE* fp;

  if (argc != 7) {
    fprintf(stderr,"Usage: mbin Mmin Mmax nbin inputfile outputfile Lbox %d \n", argc);
    exit(1);
  }
  lmmin = log(atof(argv[1]));
  lmmax = log(atof(argv[2]));
  nbin = atoi(argv[3]);
  Lbox = 1000*atoi(argv[6]);
  dlm = (lmmax-lmmin)/nbin;
  ma = calloc(nbin, sizeof(double));
  for (j=0; j<8; j++) na[j] = calloc(nbin, sizeof(int));

  fp = fopen(argv[4], "r");
  while (!feof(fp)) if (fgets(string, 999, fp)) 
    if (sscanf(string, "%*d %lf %*d %lf %lf %lf",&m,x,x+1,x+2)==4) {
      i = floor((log(m)-lmmin)/dlm);
      j = rint(x[0]/Lbox) + 2*rint(x[1]/Lbox) + 4*rint(x[2]/Lbox);
      if (i>=0 && i<nbin) {++(na[j][i]); ma[i] += m;}
    }
  fclose(fp);
  fp = fopen(argv[5], "w");
  for (i=0; i<nbin; i++) {
    for (s=s2=j=0; j<8; j++) {
      s += na[j][i];  s2 += na[j][i]*na[j][i];
    }
    ma[i] /= s;
    s2 = sqrt((8*s2 - s*s)/7);
    fprintf(fp,"%g %g %g\n", ma[i], s/dlm, s2/dlm);
  }
  free(ma);
  for (j=0; j<8; j++) free(na[j]);
  fclose(fp);
  return 0;
}
